import time
from selenium import webdriver
import json


def write_local_file(filename,text):
    with open(filename,"w",encoding="utf-8") as file:
        file.write(text)
        file.close()

def fetch_website(url):
    driver = webdriver.Firefox()
    driver.get(url)
    return driver

def qianfeng_login(driver,url):
    """
    (1)  模拟登陆
    (2)  产生快照
    (3)  保存cookie
    (4)  实现免密登陆
    :param url:
    :return:
    """
    # driver = fetch_website(url)
    time.sleep(1)
    driver.find_element_by_name("Account").send_keys("421083199405194730")
    driver.find_element_by_name("PassWord").send_keys("194730")
    driver.find_element_by_xpath('//form/fieldset/div/button').click()
    time.sleep(1)
    # 快照
    driver.save_screenshot()
    # 保存cookie并退出
    store_cookies(driver)
    driver_wait(driver)


# 保存cookie
def store_cookies(driver):
    cookie_dic = driver.get_cookie()
    cookie_str = json.dumps(cookie_dic)
    write_local_file("qf_COOKIE",cookie_str)

    # response = driver.page_source
    # write_local_file("email_login.html",response)
def driver_wait(driver):
    time.sleep(10)
    driver.quit()

# 免密登陆
def login_without_account(driver,url):
    driver.delete_all_cookies()
    with open("qf_COOKIE","r",encoding="utf-8") as file:
        json_content = file.read()
        json_content_dir = json.loads(json_content)
        for cookie in json_content_dir:
            driver.add_cookie(cookie)

if __name__ == "__main__":
    url = "http://stu.1000phone.net/student.php/Public/login"
    # 获取driver
    driver = fetch_website(url)
    # 账号登录
    qianfeng_login(driver,url)
    # 免密登陆
    login_without_account(driver,url)